<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const conversationId = route.params.conversationId as string

// 定义AI模型接口
interface AiModel {
  id: number;
  name: string;
  modelKey: string;
  icon: string;
  iconClass: string;
  colorClass: string;
  selected: boolean;
  free: boolean;
  modelDescription?: string;
  rankPosition?: number;
  flowersCount?: number;
  eggsCount?: number;
  popularityScore?: number;
  discussionsCount?: number;
  responseSpeedScore?: number;
  accuracyScore?: number;
  copywritingScore?: number;
  drawingScore?: number;
  programmingScore?: number;
}

// 定义聊天历史项接口
interface ChatHistoryItem {
  question: string;
  responses: any;
  timestamp: Date;
}

// 定义流式响应接口
interface StreamResponse {
  modelKey: string;
  modelName: string;
  content: string;
  thinkingContent: string;
  status: 'streaming' | 'success' | 'error';
  error?: string;
  timestamp?: Date;
}

// 历史记录相关状态
const showHistoryDialog = ref(false)
const historyLoading = ref(false)
const conversationHistory = ref<ConversationHistoryItem[]>([])

// 定义历史记录项接口
interface ConversationHistoryItem {
  conversationId: string
  question: string
  timestamp: Date
  modelCount: number
  models: string[]
}

const chatHistory = ref<ChatHistoryItem[]>([])
const currentQuestion = ref('')
const isProcessing = ref(false)
const chatInput = ref('')

const aiModels = ref<AiModel[]>([])
const selectedModelsForChat = ref<AiModel[]>([])

// 流式响应状态管理
const currentStreamingResponses = ref<{ [key: string]: StreamResponse }>({})

// 添加思考过程展开状态管理
const thinkingExpanded = ref<{ [key: string]: boolean }>({})

// 切换思考过程展开状态
const toggleThinking = (modelKey: string) => {
  thinkingExpanded.value[modelKey] = !thinkingExpanded.value[modelKey]
}

// 检查思考过程是否展开
const isThinkingExpanded = (modelKey: string) => {
  return thinkingExpanded.value[modelKey] || false
}

// 计算属性：按时间分组的历史记录
const groupedHistory = computed(() => {
  const today = new Date()
  const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const sevenDaysAgo = new Date(todayStart.getTime() - 7 * 24 * 60 * 60 * 1000)
  const thirtyDaysAgo = new Date(todayStart.getTime() - 30 * 24 * 60 * 60 * 1000)
  
  const todayRecords: ConversationHistoryItem[] = []
  const recentRecords: ConversationHistoryItem[] = []
  const olderRecords: ConversationHistoryItem[] = []
  
  conversationHistory.value.forEach(item => {
    const itemDate = new Date(item.timestamp)
    
    if (itemDate >= todayStart) {
      todayRecords.push(item)
    } else if (itemDate >= sevenDaysAgo) {
      recentRecords.push(item)
    } else if (itemDate >= thirtyDaysAgo) {
      olderRecords.push(item)
    }
  })
  
  return {
    today: todayRecords,
    recent: recentRecords,
    older: olderRecords
  }
})

// 获取AI模型数据
const fetchAiModels = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/ai-models/active`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        aiModels.value = result.data.map((model: any) => {
          return {
            id: model.id,
            name: model.displayName,
            modelKey: model.name,
            icon: model.icon,
            iconClass: model.iconClass || 'fas fa-robot',
            colorClass: model.colorClass || 'bg-gray-100 text-gray-600',
            selected: false,
            free: model.isFree,
            modelDescription: model.modelDescription,
            rankPosition: model.rankPosition,
            flowersCount: model.flowersCount,
            eggsCount: model.eggsCount,
            popularityScore: model.popularityScore,
            discussionsCount: model.discussionsCount,
            responseSpeedScore: model.responseSpeedScore,
            accuracyScore: model.accuracyScore,
            copywritingScore: model.copywritingScore,
            drawingScore: model.drawingScore,
            programmingScore: model.programmingScore
          }
        })
      }
    }
  } catch (error) {
    console.error('获取AI模型错误:', error)
  }
}

// 加载对话详情
const loadConversationDetails = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/conversation/${conversationId}`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        // 加载对话历史到chatHistory
        chatHistory.value = result.data.messages || []
        
        // 设置选中的模型
        if (result.data.models) {
          selectedModelsForChat.value = result.data.models.map((modelInfo: any) => {
            const model = aiModels.value.find(m => m.id === modelInfo.id)
            return model || {
              id: modelInfo.id,
              name: modelInfo.name,
              modelKey: modelInfo.modelKey,
              iconClass: 'fas fa-robot',
              colorClass: 'bg-gray-100 text-gray-600',
              selected: false,
              free: false
            }
          })
        }
      }
    }
  } catch (error) {
    console.error('加载对话详情失败:', error)
    ElMessage.error('加载对话详情失败')
  }
}

// 更新流式响应的辅助函数
const updateStreamingResponse = (modelKey: string, updates: Partial<StreamResponse>) => {
  if (currentStreamingResponses.value[modelKey]) {
    currentStreamingResponses.value[modelKey] = {
      ...currentStreamingResponses.value[modelKey],
      ...updates
    }
  } else {
    currentStreamingResponses.value[modelKey] = {
      modelKey,
      modelName: '',
      content: '',
      thinkingContent: '',
      status: 'streaming',
      timestamp: new Date(),
      ...updates
    }
  }
}

// 处理流式响应
const handleStreamResponse = async (model: AiModel, question: string) => {
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
  
  const payload = {
    question: question,
    modelId: model.id,
    conversationId: conversationId,
    history: chatHistory.value,
    contextSize: 5
  }
  
  try {
    const response = await fetch(`${baseURL}/chat/ask-stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 初始化流式响应状态
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'streaming',
      timestamp: new Date()
    })
    
    // 处理 Server-Sent Events 流
    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }
    
    const decoder = new TextDecoder()
    let buffer = ''
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        updateStreamingResponse(model.modelKey, {
          status: 'success',
          timestamp: new Date()
        })
        break
      }
      
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        if (line.trim() === '') continue
        
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          
          try {
            const streamingOutput = JSON.parse(data)
            
            if (streamingOutput.type === 'thinking' && streamingOutput.data) {
              const currentThinking = currentStreamingResponses.value[model.modelKey]?.thinkingContent || ''
              updateStreamingResponse(model.modelKey, {
                thinkingContent: currentThinking + streamingOutput.data
              })
            } else if (streamingOutput.type === 'content' && streamingOutput.data) {
              const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
              updateStreamingResponse(model.modelKey, {
                content: currentContent + streamingOutput.data
              })
            } else if (streamingOutput.type === 'done') {
              updateStreamingResponse(model.modelKey, {
                status: 'success',
                timestamp: new Date()
              })
              return
            } else if (streamingOutput.type === 'error') {
              updateStreamingResponse(model.modelKey, {
                status: 'error',
                error: streamingOutput.data || '未知错误',
                timestamp: new Date()
              })
              return
            }
          } catch (parseError) {
            console.warn('解析流式输出失败:', parseError)
            const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
            updateStreamingResponse(model.modelKey, {
              content: currentContent + data
            })
          }
        }
      }
    }
    
  } catch (error) {
    console.error(`模型 ${model.name} 流式请求失败:`, error)
    
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'error',
      error: error instanceof Error ? error.message : '网络错误',
      timestamp: new Date()
    })
  }
}

// 发送消息
const sendMessage = async () => {
  if (!chatInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  const newQuestion = chatInput.value
  chatInput.value = ''
  currentQuestion.value = newQuestion
  isProcessing.value = true
  
  currentStreamingResponses.value = {}
  
  try {
    // 并发启动多个流式请求
    const streamPromises = selectedModelsForChat.value.map(model => 
      handleStreamResponse(model, newQuestion)
    )
    
    // 等待所有流式请求完成
    await Promise.allSettled(streamPromises)
    
    // 将流式响应保存到聊天历史
    chatHistory.value.push({
      question: newQuestion,
      responses: { ...currentStreamingResponses.value },
      timestamp: new Date()
    })
    
    // 清空当前流式响应
    currentStreamingResponses.value = {}
    
    ElMessage.success('消息发送成功')
    
  } catch (error) {
    console.error('发送消息错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 获取模型响应数据
const getModelResponse = (modelKey: string) => {
  return currentStreamingResponses.value[modelKey]
}

// 格式化时间戳
const formatTimestamp = (timestamp: Date | string | undefined) => {
  if (!timestamp) return '未知时间'
  
  try {
    const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp
    return date.toLocaleString().substring(5, 16)
  } catch (error) {
    return '时间格式错误'
  }
}

// 格式化时间显示
const formatHistoryTime = (timestamp: Date) => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return timestamp.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 格式化详细时间显示
const formatDetailedTime = (timestamp: Date) => {
  if (!timestamp) return '未知时间'
  
  try {
    const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '时间格式错误'
  }
}

// 计算思考过程时长
const getThinkingDuration = (modelKey: string) => {
  const response = currentStreamingResponses.value[modelKey]
  if (!response || !response.timestamp) return 0
  
  const startTime = new Date(response.timestamp).getTime()
  const endTime = new Date().getTime()
  const duration = Math.floor((endTime - startTime) / 1000)
  
  return Math.max(0, duration)
}

// 根据modelKey获取对应的displayName
const getModelDisplayName = (modelKey: string) => {
  const selectedModel = selectedModelsForChat.value.find(model => model.modelKey === modelKey)
  if (selectedModel) {
    return selectedModel.name
  }
  
  const allModel = aiModels.value.find(model => model.modelKey === modelKey)
  if (allModel) {
    return allModel.name
  }
  
  return modelKey
}

// 根据模型名称获取图标和颜色
const getModelDisplayConfig = (modelName: string) => {
  const model = aiModels.value.find(m => m.name === modelName || m.modelKey === modelName)
  if (model) {
    return {
      iconClass: model.iconClass || 'fas fa-robot',
      colorClass: model.colorClass || 'bg-gray-100 text-gray-600'
    }
  }
  
  return { iconClass: 'fas fa-robot', colorClass: 'bg-gray-100 text-gray-600' }
}

// 获取当前用户ID
const getCurrentUserId = (): string => {
  return localStorage.getItem('userId') || 'anonymous'
}

// 获取历史记录数据
const fetchConversationHistory = async () => {
  try {
    historyLoading.value = true
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const userId = getCurrentUserId()
    
    const response = await fetch(`${baseURL}/chat/history?userId=${userId}`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        conversationHistory.value = result.data.map((item: any) => ({
          conversationId: item.conversationId,
          question: item.question,
          timestamp: new Date(item.timestamp),
          modelCount: item.modelCount || 0,
          models: item.models || []
        }))
        console.log('历史记录加载成功:', conversationHistory.value)
      } else {
        ElMessage.error('获取历史记录失败: ' + result.message)
      }
    } else {
      ElMessage.error('获取历史记录失败')
    }
  } catch (error) {
    console.error('获取历史记录错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    historyLoading.value = false
  }
}

// 显示历史记录对话框
const showHistory = async () => {
  showHistoryDialog.value = true
  await fetchConversationHistory()
}

// 关闭历史记录对话框
const closeHistoryDialog = () => {
  showHistoryDialog.value = false
}

// 清空账号历史
const clearAccountHistory = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const userId = getCurrentUserId()
    
    const response = await fetch(`${baseURL}/chat/history/clear?userId=${userId}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      conversationHistory.value = []
      ElMessage.success('历史记录已清空')
    } else {
      ElMessage.error('清空失败')
    }
  } catch (error) {
    console.error('清空历史记录失败:', error)
    ElMessage.error('清空失败')
  }
}

// 点击历史记录项
const selectHistoryItem = (conversationId: string) => {
  // 跳转到独立的聊天页面
  router.push(`/chat/${conversationId}`)
}

// 删除历史记录 - 添加确认框
const deleteHistoryItem = async (conversationId: string) => {
  try {
    // 使用 ElMessageBox 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这条历史记录吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/history/${conversationId}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      // 从本地列表中移除
      conversationHistory.value = conversationHistory.value.filter(
        item => item.conversationId !== conversationId
      )
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不显示错误信息
      return
    }
    console.error('删除历史记录失败:', error)
    ElMessage.error('删除失败')
  }
}

// 按钮事件处理
const handleMicrophone = () => {
  ElMessage.info('语音功能开发中...')
}

const handleUpload = () => {
  ElMessage.info('上传功能开发中...')
}

// 组件挂载时加载数据
onMounted(async () => {
  await fetchAiModels()
  await loadConversationDetails()
})
</script>

<template>
  <div class="bg-white h-screen overflow-hidden">
    <!-- 整体布局：左侧导航 + 右侧内容 -->
    <div class="flex">
      <!-- 左侧固定导航栏 -->
      <div class="w-[119px] bg-white flex flex-col sticky top-0 h-screen">
        <div class="p-6 text-center">
          <div class="font-['Pacifico'] text-2xl text-primary tracking-wider">AI Chat</div>
        </div>
        <div class="px-4 py-4 flex flex-col items-center text-center">
          <div class="w-16 h-16 bg-gradient-to-r from-primary to-secondary rounded-full flex items-center justify-center text-white shadow-lg mb-3">
            <span class="text-2xl font-semibold">M</span>
          </div>
          <div class="text-base font-medium tracking-wide">默默</div>
          <div class="text-sm text-gray-600 flex items-center mt-1">
            <i class="fas fa-crown text-yellow-400 mr-1"></i>
            <span class="font-medium">VIP会员</span>
          </div>
        </div>
        <nav class="flex-1 px-3 py-6">
          <div class="space-y-2">
            <a 
              @click="showHistory" 
              class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors cursor-pointer"
            >
              <i class="fas fa-history w-5 h-5 text-primary mb-1"></i>
              <span class="font-medium text-sm tracking-wide">历史记录</span>
            </a>
            <a href="#" class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors">
              <i class="fas fa-star w-5 h-5 mb-1"></i>
              <span class="font-medium text-sm tracking-wide">收藏夹</span>
            </a>
            <a href="#" class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors">
              <i class="fas fa-cog w-5 h-5 mb-1"></i>
              <span class="font-medium text-sm tracking-wide">设置</span>
            </a>
          </div>
        </nav>
      </div>

      <!-- 历史记录侧边栏 - 紧靠浏览器左侧 -->
      <div 
        v-if="showHistoryDialog" 
        class="fixed left-0 top-0 h-full w-80 bg-white shadow-2xl z-50 flex flex-col border-r border-gray-200"
      >
        <!-- 对话框头部 -->
        <div class="flex items-center justify-between p-4 bg-gray-50">
          <h3 class="text-lg font-semibold text-gray-800">历史记录</h3>
          <div class="flex items-center space-x-2">
            <button 
              @click="clearAccountHistory"
              class="px-3 py-1 text-sm text-gray-600 bg-gray-200 rounded-md hover:bg-gray-300 transition-colors"
            >
              清空账号历史
            </button>
            <button 
              @click="closeHistoryDialog"
              class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors"
            >
              ✕
            </button>
          </div>
        </div>
        
        <!-- 对话框内容 -->
        <div class="flex-1 overflow-y-auto">
          <div v-if="historyLoading" class="flex items-center justify-center py-8">
            <i class="fas fa-spinner fa-spin text-2xl text-primary mr-3"></i>
            <span class="text-gray-600">加载中...</span>
          </div>
          
          <div v-else-if="conversationHistory.length === 0" class="text-center py-8 px-4">
            <i class="fas fa-history text-4xl text-gray-300 mb-4"></i>
            <p class="text-gray-500">暂无历史记录</p>
          </div>
          
          <div v-else class="p-4 space-y-6">
            <!-- 今天 -->
            <div v-if="groupedHistory.today.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-day mr-2"></i>
                今天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.today" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                        <span class="mx-2">•</span>
                        <span>{{ formatDetailedTime(item.timestamp) }}</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 近7天 -->
            <div v-if="groupedHistory.recent.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-week mr-2"></i>
                近7天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.recent" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                        <span class="mx-2">•</span>
                        <span>{{ formatDetailedTime(item.timestamp) }}</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 近30天 -->
            <div v-if="groupedHistory.older.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-alt mr-2"></i>
                近30天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.older" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                        <span class="mx-2">•</span>
                        <span>{{ formatDetailedTime(item.timestamp) }}</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 对话框底部 -->
        <div class="p-4 border-t border-gray-200 bg-gray-50 rounded-b-2xl">
          <div class="text-center text-sm text-gray-500">
            共 {{ conversationHistory.length }} 条记录
          </div>
        </div>
      </div>

      <!-- 历史对话区 -->
      <div class="w-60 bg-white flex flex-col sticky top-0 h-screen">
        <div class="p-4">
          <div class="font-medium text-base mb-4">当前对话目录</div>
          <div class="space-y-4 overflow-y-auto flex-1">
            <div 
              v-for="(item, index) in chatHistory" 
              :key="index"
              class="bg-gray-50 rounded-lg p-3 cursor-pointer hover:bg-gray-100"
            >
              <!-- 问题显示 -->
              <div class="text-sm font-medium mb-3 text-gray-800">{{ item.question.substring(0, 15) }}...</div>
              
              <!-- 模型回答列表 -->
              <div class="space-y-2">
                <div 
                  v-for="(response, modelName) in item.responses" 
                  :key="modelName"
                  class="bg-white rounded-lg p-2"
                >
                  <div class="flex items-center mb-1">
                    <!-- 模型图标 -->
                    <div :class="['w-4 h-4 rounded flex items-center justify-center mr-2', getModelDisplayConfig(String(modelName)).colorClass]">
                      <i :class="[getModelDisplayConfig(String(modelName)).iconClass, 'text-xs']"></i>
                    </div>
                    <!-- 模型名称 -->
                    <span class="text-xs font-medium text-gray-700">{{ getModelDisplayName(String(modelName)) }}的回答</span>
                  </div>
                  <!-- 回答内容预览 -->
                  <div class="text-xs text-gray-500 line-clamp-2">
                    {{ typeof response === 'string' ? response.substring(0, 30) + '...' : (response?.content || 'AI回复').substring(0, 30) + '...' }}
                  </div>
                </div>
              </div>
              
              <!-- 时间戳 -->
              <div class="text-xs text-gray-400 mt-2">{{ item.timestamp.toLocaleString().substring(0, 16) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="flex-1 h-screen overflow-y-auto pr-4">
        <div class="max-w-4xl mx-auto p-6 pb-40">
          <!-- 聊天内容滚动区域 -->
          <div class="flex-1 overflow-y-auto pr-2">
            <!-- 历史对话区域 -->
            <div v-for="(item, index) in chatHistory" :key="index" class="mb-8">
              <!-- 用户问题 -->
              <div class="flex justify-end mb-6">
                <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
                  <div class="text-lg font-medium text-gray-800">{{ item.question }}</div>
                </div>
              </div>

              <!-- AI模型响应 -->
              <div 
                v-for="model in selectedModelsForChat" 
                :key="`history-${index}-${model.id}`"
                class="mb-8"
              >
                <div class="bg-white rounded-xl pl-0 pt-0 pb-5 border-gray-100">
                  <div class="flex items-center mb-4">
                    <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                      <i :class="[model.iconClass, 'text-sm']"></i>
                    </div>
                    <span class="font-medium text-gray-800">{{ model.name }}</span>
                  </div>
                  <div class="text-gray-700">
                    <div class="prose prose-sm max-w-none">
                      <!-- 思考过程 -->
                      <div v-if="item.responses[model.modelKey]?.thinkingContent" class="mb-4">
                        <div class="bg-gray-50 rounded-lg border border-gray-200">
                          <div 
                            @click="toggleThinking(`history-${index}-${model.modelKey}`)"
                            class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                          >
                            <div class="flex items-center">
                              <span class="text-sm font-medium text-gray-800">思考过程</span>
                              <span class="text-xs text-gray-600 ml-2">
                                ({{ item.responses[model.modelKey]?.thinkingContent?.length || 0 }} 字符)
                              </span>
                            </div>
                          </div>
                          <div 
                            v-show="isThinkingExpanded(`history-${index}-${model.modelKey}`)"
                            class="px-4 pb-4 border-t border-gray-200"
                          >
                            <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">
                              {{ item.responses[model.modelKey]?.thinkingContent }}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 回答内容 -->
                      <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                        {{ item.responses[model.modelKey]?.content || '暂无回复内容' }}
                      </div>
                      <div class="text-xs text-gray-400 mt-3">
                        回复时间：{{ formatTimestamp(item.responses[model.modelKey]?.timestamp) }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 当前对话区域 -->
            <div v-if="isProcessing || Object.keys(currentStreamingResponses).length > 0" class="mb-8">
              <!-- 当前用户问题 -->
              <div class="flex justify-end mb-6">
                <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
                  <div class="text-lg font-medium text-gray-800">{{ currentQuestion }}</div>
                </div>
              </div>

              <!-- 当前AI模型响应 -->
              <div 
                v-for="model in selectedModelsForChat" 
                :key="`current-${model.id}`"
                class="mb-8"
              >
                <div class="bg-white rounded-xl pl-0 pt-0 pb-5 border-gray-100">
                  <div class="flex items-center mb-4">
                    <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                      <i :class="[model.iconClass, 'text-sm']"></i>
                    </div>
                    <span class="font-medium text-gray-800">{{ model.name }}</span>
                  </div>
                  <div>
                    <div v-if="isProcessing && !getModelResponse(model.modelKey)" class="flex items-center text-gray-500">
                      <i class="fas fa-spinner fa-spin mr-2"></i>
                      <span>AI正在思考中...</span>
                    </div>
                    <div v-else class="text-gray-700">
                      <!-- 可折叠的思考过程显示 -->
                      <div v-if="getModelResponse(model.modelKey)?.thinkingContent" class="mb-4">
                        <div class="bg-gray-50 rounded-lg border border-gray-200">
                          <div 
                            @click="toggleThinking(model.modelKey)"
                            class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                          >
                            <div class="flex items-center">
                              <span class="text-sm font-medium text-gray-800">思考过程</span>
                              <span class="text-xs text-gray-600 ml-2">
                                ({{ getModelResponse(model.modelKey)?.thinkingContent?.length || 0 }} 字符, {{ getThinkingDuration(model.modelKey) }} 秒)
                              </span>
                            </div>
                          </div>
                          
                          <div 
                            v-show="isThinkingExpanded(model.modelKey)"
                            class="px-4 pb-4 border-t border-gray-200"
                          >
                            <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">
                              {{ getModelResponse(model.modelKey)?.thinkingContent }}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 流式响应内容 -->
                      <div v-if="getModelResponse(model.modelKey)?.status === 'streaming'" class="prose prose-sm max-w-none">
                        <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                          {{ getModelResponse(model.modelKey)?.content || '正在生成回答...' }}
                        </div>
                        <div class="text-xs text-gray-400 mt-3">
                          正在流式输出中...
                        </div>
                      </div>
                      <!-- 成功响应 -->
                      <div v-else-if="getModelResponse(model.modelKey)?.status === 'success'" class="prose prose-sm max-w-none">
                        <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                          {{ getModelResponse(model.modelKey)?.content || '暂无回复内容' }}
                        </div>
                        <div class="text-xs text-gray-400 mt-3">
                          回复时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                        </div>
                      </div>
                      <!-- 错误响应 -->
                      <div v-else-if="getModelResponse(model.modelKey)?.status === 'error'" class="text-red-600">
                        <div class="flex items-start">
                          <i class="fas fa-exclamation-triangle mr-2 mt-1 flex-shrink-0"></i>
                          <div>
                            <div class="font-medium mb-1">请求失败</div>
                            <div class="text-sm text-red-500">{{ getModelResponse(model.modelKey)?.error || '未知错误' }}</div>
                            <div class="text-xs text-gray-400 mt-2">
                              错误时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 无响应数据 -->
                      <div v-else class="text-gray-500 italic">
                        <i class="fas fa-clock mr-2"></i>
                        等待响应中...
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 固定底部输入框 - 添加返回首页按钮 -->
    <div class="fixed bottom-0 left-[179px] right-0 bg-transparent z-50">
      <div class="max-w-4xl mx-auto pl-6 pr-6 pt-6 pb-0">
        <div class="bg-white rounded-1xl border-gray-200 pt-0 pb-6">
          <!-- 顶部返回按钮区域 -->
          <div class="flex justify-end mb-0 mr-3 p-3">
            <button @click="router.push('/')" class="text-primary hover:text-primary/80 font-medium text-sm flex items-center">
              <i class="fas fa-home mr-2"></i>
              返回首页
            </button>
          </div>
          <div class="bg-white rounded-2xl border border-gray-200 p-6">
            <div class="relative">
              <textarea 
                v-model="chatInput"
                class="w-full border-none bg-gray-50/70 rounded-2xl pl-6 pr-32 py-5 resize-none focus:ring-2 focus:ring-primary focus:outline-none text-base" 
                rows="3" 
                placeholder="继续对话..."
              ></textarea>
              <div class="absolute right-4 bottom-4 flex items-center space-x-2">
                <button @click="handleMicrophone" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-microphone"></i>
                </button>
                <button @click="handleUpload" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-paperclip"></i>
                </button>
                <button @click="sendMessage" class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90">
                  <i class="fas fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
